package com.xpmusic.controller;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 防止用户直接通过地址栏访问music目录
 */
public class MusicFilter implements Filter {
    public void destroy() {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
    
        String referer=request.getHeader("Referer");
        //获取发送请求的服务器的主机名
        String sitePart="http://"+request.getServerName();
        //判断referer是否为空，这个头的首地址是否以sitePart开始的
        if (referer!=null && referer.startsWith(sitePart)){
            chain.doFilter(req, resp);
        }else{
            response.getWriter().write("你没有权限访问此资源！");
        }
    }
    
    public void init(FilterConfig config) throws ServletException {
    }
}
